package com.aramis.mydytt.widget

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import com.aramis.mydytt.R

/**
 * Description: LoadingStateView
 * @author lizhidan
 * Created: 2021/5/26
 */
class LoadingStateView : RelativeLayout {
    private var loadingLayout: ViewGroup? = null
    private var loadingTextView: TextView? = null
    private var errorLayout: ViewGroup? = null
    private var errorImageView: AppCompatImageView? = null
    private var errorTextView: TextView? = null
    private var onErrorRetryListener: (() -> Unit)? = null

    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        inflate(context, R.layout.view_loading, this)
        loadingLayout = findViewById(R.id.layout_loading)
        loadingTextView = findViewById(R.id.text_loading)
        errorLayout = findViewById(R.id.layout_error_empty)
        errorImageView = findViewById(R.id.image_error)
        errorTextView = findViewById(R.id.text_error)
    }

    fun showLoading(loadingStrId: Int = R.string.loading_default) {
        dismiss()
        visibility = VISIBLE
        loadingLayout?.visibility = VISIBLE
        if (loadingStrId > 0) {
            loadingTextView?.text = context.getString(loadingStrId)
        }
    }

    fun showError(errorStrId: Int = R.string.error_default) {
        dismiss()
        visibility = VISIBLE
        errorLayout?.visibility = VISIBLE
        errorImageView?.setImageResource(R.drawable.ic_error)
        errorImageView?.setColorFilter(Color.parseColor("#FF4500"))
        errorTextView?.text = context.getString(errorStrId)
        if (onErrorRetryListener != null) {
            errorLayout?.setOnClickListener { onErrorRetryListener?.invoke() }
        }
    }

    fun showEmpty(emptyStrId: Int = R.string.empty_default) {
        dismiss()
        visibility = VISIBLE
        errorLayout?.visibility = VISIBLE
        errorImageView?.setImageResource(R.drawable.ic_empty)
        errorImageView?.setColorFilter(Color.WHITE)
        errorTextView?.text = context.getString(emptyStrId)
        errorLayout?.setOnClickListener(null)
    }

    fun dismiss() {
        visibility = GONE
        loadingLayout?.visibility = GONE
        errorLayout?.visibility = GONE
    }

    fun setOnErrorRetryListener(listener: (() -> Unit)?) {
        onErrorRetryListener = listener
    }
}